import requests
from bs4 import BeautifulSoup
from rest_framework.views import APIView
import json
from rest_framework.response import Response
from faissutils import FAISSDBUtils

from langchain_community.document_loaders import TextLoader
from langchain.text_splitter import CharacterTextSplitter

from langchain_community.llms import  Tongyi
from langchain.prompts import PromptTemplate



class MovieView(APIView):
    def get(self,request):
        res = requests.get("https://movie.douban.com/", headers={
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/132.0.0.0 Safari/537.36"
        })
        # 电影列表
        movies = []

        # print()
        # 解析库，解析网页标签
        ht = res.text
        stop = BeautifulSoup(ht, "html.parser")

        rev = stop.find_all('div', class_='review')
        # print(xx)
        for i in rev:
            # movie_link_tag = i.find('div',class_ = "review-hd").find('a')
            # print(movie_link_tag)
            movie_title_tag = i.find('div', class_="review-meta").find_all('a')[-1]
            # 电影地址
            movie_url = movie_title_tag['href']
            # print()
            # print(movie_title_tag.text)
            # 电影名称
            texy = movie_title_tag.text.strip().replace("《", "").replace("》", "")
            # print(texy)
            movies.append({"电影名称": texy, "电影地址": movie_url})

        print(movies)
        # 存入文件
        filen_name = './media/movie/movie.json'
        with open(filen_name,'w',encoding='utf-8')as file:
            json.dump(movies,file,ensure_ascii=False,indent=4)

        print("数据写入成功.....")

        # 加载文档
        docm = TextLoader(filen_name,encoding='utf-8').load()
        # 文档切分
        spliter = CharacterTextSplitter('\n',chunk_size=200,chunk_overlap=0)
        chunks = spliter.split_documents(docm)
        # 加入向量数据库

        faissdb = FAISSDBUtils()
        faissdb.add(chunks,"movie_index")


        return Response({"message":"请求成功"})
    def post(self,request):
        # 前端获取数据
        # ask = request.data.get("ask")
        ask = "麻雀"

        faissdb = FAISSDBUtils()
        res = faissdb.search(ask,2,'movie_index')
        print(res)

        # 构造提示模板  prompt
        text_template = "请帮我从以下{res}数据中返回2部电影得名称和请求地址，返回格式转换为json格式，返回格式为json，只返回json，不要推理信息，不要有任务描述信息，不需要```json格式"

        promptTemplate = PromptTemplate.from_template(text_template)

        prompt = promptTemplate.format(res=res)

        llm = Tongyi()
        data = llm.invoke(prompt)

        print(data)

        return Response({"message":"请求成功","data":data})
